<template>
  <div class="tab-container flex-1 flex-main">
    <el-empty v-if="recordForm.records.length===0" description="暂无参数配置项" style="background: #fff;">
      <template v-if="create">
        赶快去<span class="color-primary common-cursor" style="margin:auto 5px" @click="handleCreate">新增</span>吧！
      </template>
    </el-empty>
    <el-form ref="form" :loading="listLoading" :model="recordForm" label-width="200px" class="flex-1">
      <div v-for="(item,index) in recordForm.records" :key="item.id" class="flex-row">
        <div style="min-width: 600px;">
          <el-form-item :label="item.paramName+'('+item.orders+')'" :prop="'records.' + index + '.paramValue'" :rules="{required: true, message: '不能为空', trigger: 'blur'}">
            <template>
              <!--文本框-->
              <el-input v-if="item.formType==0" v-model="item.paramValue" />
              <!--单选按钮组-->
              <el-radio-group v-else-if="item.formType==1" v-model="item.paramValue">
                <el-radio
                  v-for="(optionItem) in (JSON.parse(item.formValue))"
                  :key="optionItem.key"
                  :label="optionItem.value+''">
                  {{ optionItem.label }}
                </el-radio>
              </el-radio-group>
              <!--下拉-->
              <el-select v-else-if="item.formType==2" v-model="item.paramValue" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="(optionItem) in (JSON.parse(item.formValue))"
                  :key="optionItem.key"
                  :value="optionItem.value+''"
                  :label="optionItem.label" />
              </el-select>
              <!--数字文本框-->
              <el-input v-else-if="item.formType==4" v-model="item.paramValue" type="number" />
              <!--文本域-->
              <el-input
                v-else-if="item.formType==5"
                v-model="item.paramValue"
                :rows="4"
                type="textarea"
                maxlength="200"
                show-word-limit
                placeholder="请输入(限200字以内)" />
              <single-image-upload
                v-else-if="item.formType==6"
                v-model="item.paramValue"
                :catalog="constants.FILE_CATALOG_PARAMS_CONFIG" />
              <!--富文本编辑器-->
              <Editor v-else-if="item.formType==7" v-model="item.paramValue" :catalog="constants.FILE_CATALOG_PARAMS_CONFIG" />
            </template>
            <div v-if="item.paramDesc" class="common-area-desc">
              <div v-for="desc in item.paramDesc.split('\n')" :key="desc" class="item">
                {{ desc }}
              </div>
            </div>
          </el-form-item>
        </div>
        <div style="min-width:150px">
          <copy-text :content="item.paramCode" :show="false" style="margin-right:10px" />
          <button-option v-if="create" icon="el-icon-edit" skin="primary" title="编辑配置项" @click="handleUpdate(item)" />
          <button-option v-if="remove" icon="el-icon-delete" skin="danger" title="删除" @click="handleRemove(item.id)" />
          <button-option v-if="index===0 && create" icon="el-icon-plus" skin="primary" title="新增配置项" @click="handleCreate" />
        </div>
      </div>
    </el-form>
    <div v-if="recordForm.records.length>0" class="config-footer">
      <el-button :loading="buttonLoading" type="primary" @click="handleConfig()">保存配置</el-button>
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="systemConfigRules"
          :model="systemConfigRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="配置编码" prop="paramCode">
            <el-input v-model="systemConfigRecord.paramCode" placeholder="请输入配置编码" />
          </el-form-item>
          <el-form-item label="配置名称" prop="paramName">
            <el-input v-model="systemConfigRecord.paramName" placeholder="请输入配置名称" />
          </el-form-item>
          <el-form-item label="配置排序" prop="orders">
            <el-input-number v-model="systemConfigRecord.orders" placeholder="请输入配置排序" show-word-limit :max="99" style="width:100%" />
          </el-form-item>
          <el-form-item v-if="sideBox.status==='create'" label="表单类型:" prop="formType">
            <data-dict-select v-model="systemConfigRecord.formType" :code="'formType'" placeholder="请选择表单类型" />
          </el-form-item>
          <template>
            <template v-if="systemConfigRecord.formType==='1' || systemConfigRecord.formType==='2'">
              <el-form-item label="选项:">
                <el-link type="primary" :underline="false" @click="handleAddOptionSetting">新增</el-link>
                <el-form-item
                  v-for="(optionItem) in optionSettings"
                  :key="optionItem.key"
                  :label="'参数'"
                  label-width="70px">
                  <el-row :gutter="10">
                    <el-col :span="6">
                      <el-input v-model="optionItem.value" />
                    </el-col>
                    <el-col :span="10">
                      <el-input v-model="optionItem.label" />
                    </el-col>
                    <el-col :span="7">
                      <el-link type="danger" :underline="false" @click="handleRemoveptionSetting(optionItem.key)">删除</el-link>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-form-item>
            </template>
          </template>
          <el-form-item label="配置描述:" prop="paramDesc">
            <el-input
              v-model="systemConfigRecord.paramDesc"
              :rows="4"
              type="textarea"
              maxlength="300"
              show-word-limit
              placeholder="请输入配置描述(限300字以内)" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
export default {
  components: { },
  props: {
    selectedGroup: {
      type: Object,
      default: () => {
        return {}
      }
    },
    create: {
      type: Boolean,
      default: true
    },
    remove: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      listLoading: false,
      buttonLoading: false,
      recordForm: {
        records: []
      },
      configRecords: [],
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create' // 对话框状态
      },
      systemConfigRecord: {},
      systemConfigRules: {
        formType: [
          { required: true, message: '请选择表单类型', trigger: 'blur' }
        ],
        paramCode: [
          { required: true, message: '请输入配置编码', trigger: 'blur' },
          { required: true, validator: this.$validate.validateEngOrNum, trigger: 'blur' }
        ],
        paramName: [
          { required: true, message: '请输入配置名称', trigger: 'blur' }
        ],
        orders: [
          { required: true, message: '请输入配置排序', trigger: 'blur' },
          { required: true, validator: this.$validate.validateNumber, trigger: 'blur' }
        ]
      },
      optionSettings: []
    }
  },
  watch: {
    'systemConfigRecord.formType': function(val) {
      if (val && this.sideBox.status === 'create') {
        if (val === '1' || val === '2') {
          this.optionSettings = []
          this.optionSettings.push({
            key: new Date().getTime(),
            value: 0,
            label: ''
          })
        }
      }
    },
    'selectedGroup.code': function(val) {
      this.initParams()
    }
  },
  created() {
  },
  methods: {
    async initParams() {
      this.recordForm.records = []
      this.listLoading = true
      const response = await this.$store.dispatch('listConfigByGroupCode', this.selectedGroup.code)
      this.recordForm = {
        records: response
      }
      this.listLoading = false
    },
    handleAddOptionSetting() {
      this.optionSettings.push({
        key: new Date().getTime(),
        value: this.optionSettings.length,
        label: ''
      })
    },
    handleRemoveptionSetting(key) {
      var temp = this.optionSettings.filter(item => {
        return item.key !== key
      })
      this.optionSettings = temp
    },
    handleCreate() {
      this.sideBox = {
        recordShow: true,
        status: 'create',
        title: '新增配置项'
      }
      this.systemConfigRecord = {
        orders: 1
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.systemConfigRecord = {
        ...this.systemConfigRecord,
        pid: this.selectedGroup.id
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.systemConfigRecord.formType === '1' || this.systemConfigRecord.formType === '2') {
            this.systemConfigRecord = {
              ...this.systemConfigRecord,
              formValue: JSON.stringify(this.optionSettings)
            }
          }
          this.$store.dispatch('saveConfig', this.systemConfigRecord).then(response => {
            this.$modal.msgSuccess('配置成功')
            this.systemConfigRecord = {}
            this.initParams()
            this.sideBox.recordShow = false
          }).catch(() => {
          })
        }
      })
    },

    handleConfig() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          var datas = []
          this.recordForm.records.forEach(item => {
            datas.push({
              id: item.id,
              paramValue: item.paramValue
            })
          })
          this.$store.dispatch('updateConfig', datas).then(response => {
            this.buttonLoading = false
            this.$modal.msgSuccess('修改成功')
            this.initParams()
          }).catch(() => {
            this.buttonLoading = false
          })
        } else {
          return false
        }
      })
    },
    handleRemove(id) {
      this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('systemConfigRemove', [id]).then(response => {
          this.initParams()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {})
      }).catch(() => { })
    },

    /* 编辑*/
    handleUpdate(row) {
      this.systemConfigRecord = Object.assign({}, row) // copy obj
      console.log(row)
      if (row.formValue) {
        if (row.formType === '1' || row.formType === '2') {
          this.optionSettings = JSON.parse(row.formValue)
        }
      } else {
        if (row.formType === '1' || row.formType === '2') {
          this.optionSettings = []
          this.optionSettings.push({
            key: new Date().getTime(),
            value: 0,
            label: ''
          })
        }
      }
      console.log(this.optionSettings)

      this.sideBox = {
        status: 'update',
        title: '编辑配置项',
        recordShow: true
      }
      this.isUpgrade = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.systemConfigRecord.formType === '1' || this.systemConfigRecord.formType === '2') {
            this.systemConfigRecord = {
              ...this.systemConfigRecord,
              formValue: JSON.stringify(this.optionSettings)
            }
          }
          this.$store.dispatch('configUpdate', this.systemConfigRecord).then(response => {
            this.$modal.msgSuccess('配置成功')
            this.systemConfigRecord = {}
            this.initParams()
            this.sideBox.recordShow = false
          }).catch(() => {
          })
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss"  scoped>
  .tab-container{
    height: 100%;
    overflow-y: auto;
    background: #fff;
    padding: 30px 10px 10px 20px;
  }
  .config-footer{
    height: 50px;
    border-top: 1px solid #dcdfe6;
    line-height: 50px;
    text-align:center
  }
</style>
